package com.douwong.student.fragment;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;

import com.douwong.student.R;
import com.douwong.student.activity.ShowClassExamRecordActivity;
import com.douwong.student.adapter.ClassExamRecordAdapter;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.base.BaseFragment;
import com.douwong.student.contant.CommonConfig;
import com.douwong.student.contant.NetConfig;
import com.douwong.student.interfaces.WorkResultNotify;
import com.douwong.student.model.ClassExamRecordList;
import com.douwong.student.model.ClassTestRecordInfos;
import com.douwong.student.model.RequestAction;
import com.douwong.student.popuwindow.UpLoadPopuWindow;
import com.douwong.student.task.ClassExamRecordListTask;
import com.douwong.student.task.QuestionAnswerListTask;
import com.douwong.student.utils.JsonUtils;
import com.douwong.student.utils.LogUtils;
import com.douwong.student.utils.NetUtils;
import com.douwong.student.utils.ToastUtils;
import com.douwong.student.utils.UIUtils;
import com.douwong.student.view.MyCommonCallback;
import com.douwong.student.view.PullToRefreshListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static android.R.attr.action;

/**
 * @autor yichao
 * @time 2017/5/914:06
 * @des 课堂测验记录
 */
@SuppressLint("ValidFragment")
public class ClassTestRecordFragment extends BaseFragment {
    private static final String TAG = "ClassTestRecordFragment";
    private List<ClassExamRecordList.DataBean.ItemsBean> listData;
    private UpLoadPopuWindow popu;
    private PullToRefreshListView  answer_listview;
    private ImageView statue_img;
    private ClassExamRecordAdapter mAdapter;
    private static final String MTAG = "ClassTestFragment";
    private BaseApplication mBaseApplication;
    private int mCurrentPage;
    private boolean mIsLoading = false;
    private String startTime,endTime,subjectId;
    private Context mContext;
    private final int SHOW_POPUWINDOW=2002;
    private final int DISMISS_POPUWINDOW=2003;
    private View mClassTestView;
    private Map<String, Object> mMap;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
        mBaseApplication = (BaseApplication) context.getApplicationContext();
        
    }

    @Override
    protected View getRootView(LayoutInflater inflater, ViewGroup container) {
        mClassTestView = UIUtils.inflate(R.layout.class_test_fragment);
        answer_listview = (PullToRefreshListView) mClassTestView.findViewById(R.id.answer_listview);
        statue_img = (ImageView) mClassTestView.findViewById(R.id.statue_img);
        return mClassTestView;
    }


    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SHOW_POPUWINDOW:
                    popu.showAtLocation(mClassTestView, Gravity.CENTER,0,0);
                    popu.setText("加载中...");
                    updateExamData(RequestAction.INIT, 1,false);
                    break;
                case DISMISS_POPUWINDOW:
                    popu.dismiss();
                    break;
            }

        }
    };

    @Override
    protected void initEvent() {
        super.initEvent();
        answer_listview.setOnILoadMoreListener(new PullToRefreshListView.OnILoadMoreListener() {
            @Override
            public void onLoadMore() {
                if (mIsLoading) {
                    return;
                }
                ++mCurrentPage;
                updateExamData(RequestAction.LOADMROE, mCurrentPage,false);
                mIsLoading = true;
            }
        });
        answer_listview.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {

            @Override
            public void onRefresh() {
                mCurrentPage=1;
                updateExamData(RequestAction.REFRESH, mCurrentPage,false);
            }
        });
        answer_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                //点击条目
              /*  ClassExamDetailTask task = new ClassExamDetailTask();
                task.setDetailListener(new DetailNotify() {

                    @Override
                    public void notify(int stateCode, String content) {
                        if (stateCode == ClassExamDetailTask.REQUEST_OK) {
                          //  ShowClassExamActivity.startActivity(mContext,content,listData.get(position - 1).getExResult(),listData.get(position - 1).getExYesNo());
                        }
                    }
                });
                task.execute(listData.get(position - 1).getExamineid() + "");*/
              if (!NetUtils.NetwrokIsUseful(mContext)){
                  ToastUtils.makeText(mContext,UIUtils.getString(R.string.please_connection_network));
                  return;
              }
                mMap.clear();
                mMap.put("student_id",BaseApplication.sUserBean.getUserbean().getId()+"");
                mMap.put("class_examine_id",listData.get(position-1).getExamineid()+"");
              NetUtils.Post(NetConfig.CLASS_EXAM_RECORD_RESULT,mMap,new MyCommonCallback<String>(){
                  @Override
                  public void onSuccess(String result) {
                      LogUtils.i(TAG,"点击测试条目 ：" +result);
                      if (result!=null){
                          ClassTestRecordInfos classTestRecordInfos = JsonUtils.parseString(result, ClassTestRecordInfos.class);
                          if (classTestRecordInfos!=null && classTestRecordInfos.isFlag()){

                              ShowClassExamRecordActivity.startActivity(mContext,result);


                          }else {
                              ToastUtils.makeText(mContext,"请求数据失败");
                          }


                      }



                  }

                  @Override
                  public void onError(Throwable ex, boolean isOnCallback) {
                      LogUtils.i(TAG,"点击测试条目请求失败 "+ex.toString());
                      ToastUtils.makeText(mContext,"请求数据失败");
                  }
              });







            }
        });
    }
    @Override
    protected void initData() {
        super.initData();
        mContext.registerReceiver(mReceiver,mFilter);
        mHandler.sendEmptyMessageDelayed(SHOW_POPUWINDOW,500);
        listData = new ArrayList<ClassExamRecordList.DataBean.ItemsBean>();
        popu=new UpLoadPopuWindow(mContext);
        mAdapter = new ClassExamRecordAdapter(mContext, listData);
        answer_listview.setAdapter(mAdapter);
        mMap = new HashMap<>();
    }

    IntentFilter mFilter=new IntentFilter(){
        {addAction(CommonConfig.TEST_SEARCH);}
    };

    BroadcastReceiver mReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case CommonConfig.TEST_SEARCH :
                    startTime = intent.getStringExtra("start_time");
                    endTime=intent.getStringExtra("end_time");
                    subjectId=intent.getStringExtra("subjectId");
                    break;
            }
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mReceiver!=null){
        mContext.unregisterReceiver(mReceiver);
            mReceiver=null;
        }
        if (popu!=null && popu.isShowing()){
            popu.dismiss();
        }
    }

    /**
     * 更新数据
     * @param retention
     * @param pageIndex
     * @param isSearch
     */
    protected void updateExamData(final RequestAction retention, final int pageIndex,boolean isSearch) {
        LogUtils.i(MTAG,"当前访问的RequestAction ： "+action+"____当前访问pageIndex ：  "+ pageIndex);
        ClassExamRecordListTask task = new ClassExamRecordListTask(retention, mBaseApplication,isSearch);
        task.setWorkStautsListener(new WorkResultNotify<ClassExamRecordList.DataBean.ItemsBean>() {
            @Override
            public void notify(int stateCode, List<ClassExamRecordList.DataBean.ItemsBean> arryResult) {
                if (popu!=null && popu.isShowing()){
                    mHandler.sendEmptyMessage(DISMISS_POPUWINDOW);
                }
                //处理消息
                if (RequestAction.INIT==retention){
                    //初始化
                    //有数据 。     无数据。无网络
                    if (stateCode==QuestionAnswerListTask.REQUESTOK){
                        listData.addAll(arryResult);

                        mAdapter.notifyDataSetChanged();
                    }else if (stateCode==QuestionAnswerListTask.NO_NETWOK){
                        ToastUtils.makeText(mContext,"请检查网络");
                    }

                }else if (RequestAction.REFRESH==retention){
                    //刷新
                    if (stateCode==QuestionAnswerListTask.NO_NETWOK){

                        ToastUtils.makeText(mContext,"请检查网络");
                        listData.clear();
                        answer_listview.onRefreshComplete();
                        mAdapter.notifyDataSetChanged();

                    }else if (stateCode==QuestionAnswerListTask.NO_DATA){
                        listData.clear();
                        answer_listview.onRefreshComplete();
                        mAdapter.notifyDataSetChanged();

                    }else if (stateCode==QuestionAnswerListTask.REQUESTOK){

                        listData.clear();
                        listData.addAll(arryResult);
                        answer_listview.onRefreshComplete();
                        mAdapter.notifyDataSetChanged();

                    }

                }else if (RequestAction.LOADMROE==retention){
                    //加载更多
                    mIsLoading=false;
                    if (stateCode== QuestionAnswerListTask.NO_NETWOK){
                        --mCurrentPage;
                        ToastUtils.makeText(mContext,"请检查网络");
                        answer_listview.completeLoadMore();
                        mAdapter.notifyDataSetChanged();

                    }else if (stateCode==QuestionAnswerListTask.NO_DATA){
                        --mCurrentPage;
                        answer_listview.completeLoadMore();
                        mAdapter.notifyDataSetChanged();
                        ToastUtils.makeText(mContext,"没有更多数据了");

                    }else if (stateCode==QuestionAnswerListTask.REQUESTOK){

                        listData.addAll(arryResult);
                        answer_listview.completeLoadMore();
                        mAdapter.notifyDataSetChanged();

                    }


                }




            }
        });
        task.executeOnExecutor((ExecutorService) Executors.newCachedThreadPool(),String.valueOf(pageIndex), startTime,subjectId);

    }

}
